import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.personal.dao.model.User;

public class JDBCTest {
    @SuppressWarnings("CommentedOutCode")
    public static void main(String[] args) {
        String sql = "select * from user where id = ?";
        // String sql = "insert into user (id, username) values (?, ?)";
        // String sql = "delete from user where id = ?";
        // String sql = "update user set password = ?, birthday = ? where id = 3";
        execute(sql, 1);
    }

    public static void execute(String sql, Object... params) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://120.77.1.145:3306/mybatis?serverTimezone=GMT&useUnicode=true&useUnicode=true", "root", "xly362945411~.");
            preparedStatement = connection.prepareStatement(sql);
            for (int i = 0; i < getQuestionMarkNum(sql); i++) {
                preparedStatement.setObject(i + 1, params[i]);
            }
            if (sql.trim().startsWith("select")) {
                resultSet = preparedStatement.executeQuery();
                List<User> users = new ArrayList<>();
                while (resultSet.next()) {
                    User user = new User();
                    user.setId(resultSet.getInt("id"));
                    user.setUsername(resultSet.getString("username"));
                    users.add(user);
                }
                System.out.println(users);
            }
            else {
                preparedStatement.setInt(1, 123);
                preparedStatement.setString(2, "2021-04-07");
                System.out.println(preparedStatement.executeUpdate());
            }
        }
        catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        finally {
            autoCloseable(resultSet, preparedStatement, connection);
        }
    }

    public static int getQuestionMarkNum(String sql) {
        int count = 0;
        for (String s : sql.trim().split(" ")) {
            if ("?".equals(s)) {
                count++;
            }
        }
        return count;
    }

    public static void autoCloseable(AutoCloseable... closeables) {
        for (AutoCloseable closeable : closeables) {
            if (closeable != null) {
                try {
                    closeable.close();
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
